<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminPermission;
use App\Models\AdminRole;
use App\Models\AdminUser;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RoleController extends Controller
{
    public function index() {
        $roles = AdminRole::paginate(10);
        return view('admin.role.index',compact('roles'));
    }

    public function create() {
        return view('admin.role.create');
    }

    public function doCreate(Request $request) {

        $this->validate($request,[
            'name'       => 'required',
            'description'=> 'required'
        ]);

        $new_role = AdminRole::create($request->input());

        if(!empty($new_role)){
            return redirect('admin/roles')->with('创建角色成功!');
        }else{
            return back()->withErrors('创建角色失败!');
        }
    }

    public function role(AdminUser $adminUser) {

    }


    //角色权限关系页面
    public function permission(AdminRole $adminRole) {
        $permissions = AdminPermission::paginate(10);
        return view('admin.role.permission',compact('adminRole','permissions'));
    }

    public function doPermission(Request $request,AdminRole $adminRole) {
        //dd($request->input());
        //dd($adminRole);
        $permissions  = AdminPermission::findMany($request->input('permission'));
        $myPermissions = $adminRole->permissions;

        try{
            $addPermissions = $permissions->diff($myPermissions);

            foreach ($addPermissions as $addPermission){
                $adminRole->grantPermission($addPermission);
            }

            $deletePermissions = $myPermissions->diff($permissions);
            foreach ($deletePermissions as $deletePermission){
                $adminRole->deletePermission($deletePermission);
            }

            return redirect('admin/roles');

        }catch (\Exception $e){
            return $e;
        }
    }
}
